package com.gin.kotlin.gf2gamecommunity.base.composable

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp

/**
 * 可折叠的卡片
 * @param expanded 是否展开
 * @param title 标题
 * @param onClickTitle 点击标题时的操作
 * @param content 正文
 */

@Composable
fun ExpandableCard(expanded: Boolean, title: String, onClickTitle: () -> Unit, content: @Composable () -> Unit) {
    Column(modifier = Modifier.padding(16.dp)) {
        //     标题部分
        Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier
            .fillMaxWidth()
            .clickable { onClickTitle() }) {
            Text(title, fontWeight = FontWeight.Bold, fontSize = 24.sp)
            if (expanded) Icon(Icons.Filled.KeyboardArrowDown, contentDescription = null)
            else Icon(Icons.Filled.KeyboardArrowUp, contentDescription = null)
        }
        HorizontalDivider(modifier = Modifier.height(4.dp))
        if (expanded) content()
    }
}

/**
 * 一组同类型的折叠卡片
 * @param T Any?
 * @param items List<T>
 * @param itemTitle (item: T) -> String
 * @param itemContent (item: T) -> Unit
 */
@Composable
fun <T> ExpandableCards(items: List<T>, itemTitle: (item: T) -> String, itemContent: @Composable (item: T) -> Unit) {
    var activeIndex by remember { mutableIntStateOf(0) }
    LazyColumn {
        itemsIndexed(items = items) { index: Int, item: T ->
            ExpandableCard(
                expanded = activeIndex == index,
                title = itemTitle(item),
                onClickTitle = { activeIndex = if (activeIndex == index) -1 else index },
            ) { itemContent(item) }
        }
    }
}